﻿using System;
using System.IO;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Events;
using YArchitech.Controls;
using YArchitech.LIB;
using YJKMenuAssist.Utility;

namespace YJKMenuAssist
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class MenuManageApplication : IExternalApplication
	{
		public Result OnShutdown(UIControlledApplication application)
		{
			MenuManageApplication.m_UICtrlApplication = application;
			MenuManageApplication.m_ThisApp = this;
			if (Convert.ToInt32(application.ControlledApplication.VersionNumber) < 2015)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			if (MenuManageApplication.m_MainPage != null)
			{
				MenuManageApplication.m_MainPage.SetCommandData(null);
			}
			application.ControlledApplication.DocumentOpened -= new EventHandler<DocumentOpenedEventArgs>(this.app_IniMethod);
			application.ControlledApplication.DocumentCreated -= new EventHandler<DocumentCreatedEventArgs>(this.app_IniMethod);
			application.ApplicationClosing -= new EventHandler<ApplicationClosingEventArgs>(this.app_ClosingMethod);
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public Result OnStartup(UIControlledApplication application)
		{
			if (Convert.ToInt32(application.ControlledApplication.VersionNumber) < 2015)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			MenuManageApplication.m_UICtrlApplication = application;
			MenuManageApplication.m_ThisApp = this;
			string text = Path.Combine(Product.UserDataLocation, "CustomMenu.xml");
			try
			{
				if (!File.Exists(text))
				{
					File.Copy(Path.Combine(Product.DataLocation, "CustomMenu.xml"), text);
				}
				new XmlManager(text).ImportOpeningByXml(out MenuManageApplication.m_CommandTableInfos, "Custom");
				string path = Path.Combine(Product.UserDataLocation, "KeyboardShortcuts.xml");
				if (File.Exists(path))
				{
					File.Delete(path);
				}
			}
			catch
			{
			}
			this.RegisterPage(application, MenuManageApplication.m_CommandTableInfos);
			application.ControlledApplication.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(this.app_IniMethod);
			application.ControlledApplication.DocumentCreated += new EventHandler<DocumentCreatedEventArgs>(this.app_IniMethod);
			application.ApplicationClosing += new EventHandler<ApplicationClosingEventArgs>(this.app_ClosingMethod);
			application.DockableFrameVisibilityChanged += this.DockableFrameVisibilityChanged;
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void app_Idling(object sender, IdlingEventArgs e)
		{
			UIApplication uiapplication = sender as UIApplication;
			Document document = uiapplication.ActiveUIDocument.Document;
			uiapplication.Idling -= this.app_Idling;
		}

		private void DockableFrameVisibilityChanged(object sender, DockableFrameVisibilityChangedEventArgs e)
		{
			if (Globals.sm_UserDockablePaneId == e.PaneId && !e.DockableFrameShown)
			{
				StateController.SaveState(StateController.StateEnum.SE_Hide);
			}
		}

		private void UiApp_ViewActivated(object sender, ViewActivatedEventArgs e)
		{
			PressKeys.Press("CDSCGJ", false);
		}

		private void RegisterDockableWindow(UIControlledApplication application, Guid mainPageGuid)
		{
			Globals.sm_UserDockablePaneId = new DockablePaneId(mainPageGuid);
			application.RegisterDockablePane(Globals.sm_UserDockablePaneId, "菜单收藏工具", MenuManageApplication.m_MainPage);
		}

		public bool IsMainWindowAvailable()
		{
			if (MenuManageApplication.m_MainPage == null)
			{
				return false;
			}
			bool result = true;
			try
			{
				bool isVisible = MenuManageApplication.m_MainPage.IsVisible;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		public void SetWindowVisibility(ExternalCommandData commandData, bool state)
		{
			DockablePane dockablePane = commandData.Application.GetDockablePane(Globals.sm_UserDockablePaneId);
			if (dockablePane == null)
			{
				throw new InvalidOperationException("无法识别可停靠菜单面板");
			}
			if (!this.IsMainWindowAvailable())
			{
				throw new InvalidOperationException("竖向菜单未创建");
			}
			if (state)
			{
				dockablePane.Show();
				if (MenuManageApplication.m_MainPage != null)
				{
					MenuManageApplication.m_MainPage.SetCommandData(commandData);
					return;
				}
			}
			else
			{
				dockablePane.Hide();
				if (MenuManageApplication.m_MainPage != null)
				{
					MenuManageApplication.m_MainPage.SetCommandData(null);
				}
			}
		}

		public bool CreateWindow(CommandTableInfos commandTableInfos)
		{
			bool result;
			try
			{
				MenuManageApplication.m_MainPage = new MainPage(commandTableInfos);
				result = true;
			}
			catch (Exception)
			{
				MenuManageApplication.m_MainPage = null;
				YJKMessageBox.Show("竖向菜单窗口创建失败");
				result = false;
			}
			return result;
		}

		public void app_IniMethod(object obj, EventArgs args)
		{
			DocumentCreatedEventArgs documentCreatedEventArgs = args as DocumentCreatedEventArgs;
			if (documentCreatedEventArgs != null && documentCreatedEventArgs.Document.IsFamilyDocument)
			{
				return;
			}
			DocumentOpenedEventArgs documentOpenedEventArgs = args as DocumentOpenedEventArgs;
			if (documentOpenedEventArgs != null && documentOpenedEventArgs.Document.ActiveView == null)
			{
				return;
			}
			if (StateController.GetState() == StateController.StateEnum.SE_Uninit_Show)
			{
				PressKeys.Press("CDSCGJ", false);
			}
			PressKeys.PressEsc();
		}

		public void app_ClosingMethod(object obj, EventArgs args)
		{
			StateController.StateEnum state = StateController.StateEnum.SE_Uninit_Hide;
			if (StateController.GetState() == StateController.StateEnum.SE_Show)
			{
				PressKeys.Press("CONSC", false);
				state = StateController.StateEnum.SE_Uninit_Show;
			}
			StateController.SaveState(state);
		}

		public void RegisterPage(UIControlledApplication application, CommandTableInfos commandTableInfos)
		{
			if (!this.CreateWindow(commandTableInfos))
			{
				return;
			}
            MenuManageApplication.m_MainPage.SetInitialDockingParameters(0, 150, 0, 700, (DockPosition)(59421), Guid.Empty);
			try
			{
				this.RegisterDockableWindow(application, Globals.sm_UserDockablePaneId.Guid);
			}
			catch (Exception ex)
			{
				TaskDialog.Show("菜单收藏工具", ex.Message);
			}
		}

		internal static MainPage m_MainPage;

		internal static UIControlledApplication m_UICtrlApplication;

		internal static MenuManageApplication m_ThisApp;

		internal static CommandTableInfos m_CommandTableInfos;
	}
}
